#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    string decodeString(string s) {
        stack<string> sts;
        stack<int> sti;
        int i = 0;
        string ret;
        while (i < s.size())
        {
            if (s[i] >= '0' && s[i] <= '9')
            {
                int t = 0;
                while (i < s.size() && s[i] >= '0' && s[i] <= '9') t = t * 10 + s[i++] - '0';
                sti.push(t);
            }
            else if (s[i] == '[')
            {
                i++;
                string tmps;
                while (i < s.size() && s[i] >= 'a' && s[i] <= 'z') tmps.push_back(s[i++]);
                sts.push(tmps);
            }
            else if (s[i] == ']')
            {
                int ti = sti.top();
                string st = sts.top(), cur;
                for (int i = 0; i < ti; i++) cur += st;
                sti.pop(), sts.pop();
                if (sts.size())
                {
                    string stw = sts.top();
                    stw += cur;
                    sts.pop();
                    sts.push(stw);
                }
                else ret += cur;
                i++;
            }
            else
            {
                string tmps;
                while (i < s.size() && s[i] >= 'a' && s[i] <= 'z') tmps.push_back(s[i++]);
                if (sts.size())
                {
                    string stw = sts.top();
                    stw += tmps;
                    sts.pop();
                    sts.push(stw);
                }
                else ret += tmps;
            }
        }
        return ret;
    }
};